<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // var longestPrefix = function (s) {
    //   const length = s.length;
    //   if (length === 1) return '';
    //   for (let i = 1; i < length; i++) {
    //     const pre = s.slice(0, length - i);
    //     const suf = s.slice(i, length);
    //     if (pre === suf) return pre;
    //   }
    //   return '';
    // };


    function longestPrefix(s) {
      let l = s.length
      let next = [0]
      for (let i = 1, j = 0; i < l; i++) {
        while (j > 0 && s[i] !== s[j]) {
          j = next[j - 1]
        }
        if (s[i] === s[j]) {
          j++
        }
        next[i] = j
      }
      return s.slice(0, next[l - 1])
    };
    console.log(longestPrefix("ababab"));
  </script>
</body>

</html>